<template>
  <div class="leave-add-page">
    <!-- 导航栏 -->
    <NavBar title="申请请假" />
    
    <!-- 表单内容 -->
    <div class="page-content">
      <van-form @submit="handleSubmit">
        <!-- 请假类型 -->
        <van-field name="type" label="请假类型">
          <template #input>
            <van-picker
              v-model="form.type"
              :columns="leaveTypes"
              @confirm="onTypeConfirm"
            />
          </template>
        </van-field>
        
        <!-- 请假标题 -->
        <van-field
          v-model="form.title"
          name="title"
          label="请假标题"
          placeholder="请输入请假标题"
          :rules="[{ required: true, message: '请输入请假标题' }]"
        />
        
        <!-- 开始时间 -->
        <van-field
          v-model="form.startDate"
          name="startDate"
          label="开始时间"
          placeholder="选择开始时间"
          readonly
          @click="showStartPicker = true"
          :rules="[{ required: true, message: '请选择开始时间' }]"
        />
        
        <!-- 结束时间 -->
        <van-field
          v-model="form.endDate"
          name="endDate"
          label="结束时间"
          placeholder="选择结束时间"
          readonly
          @click="showEndPicker = true"
          :rules="[{ required: true, message: '请选择结束时间' }]"
        />
        
        <!-- 请假原因 -->
        <van-field
          v-model="form.reason"
          name="reason"
          label="请假原因"
          type="textarea"
          placeholder="请详细说明请假原因"
          rows="4"
          :rules="[{ required: true, message: '请输入请假原因' }]"
        />
        
        <!-- 联系方式 -->
        <van-field
          v-model="form.contactWay"
          name="contactWay"
          label="联系方式"
          placeholder="请输入联系方式"
          :rules="[{ required: true, message: '请输入联系方式' }]"
        />
        
        <!-- 附件上传 -->
        <van-field name="attachments" label="相关附件">
          <template #input>
            <van-uploader
              v-model="form.attachments"
              multiple
              :max-count="3"
              :after-read="afterRead"
            />
          </template>
        </van-field>
        
        <!-- 提交按钮 -->
        <div class="submit-section">
          <van-button
            round
            block
            type="primary"
            native-type="submit"
            :loading="loading"
          >
            提交请假申请
          </van-button>
        </div>
      </van-form>
    </div>
    
    <!-- 时间选择器 -->
    <van-popup v-model:show="showStartPicker" position="bottom">
      <van-datetime-picker
        v-model="startDateTime"
        type="datetime"
        title="选择开始时间"
        @confirm="onStartConfirm"
        @cancel="showStartPicker = false"
      />
    </van-popup>
    
    <van-popup v-model:show="showEndPicker" position="bottom">
      <van-datetime-picker
        v-model="endDateTime"
        type="datetime"
        title="选择结束时间"
        @confirm="onEndConfirm"
        @cancel="showEndPicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import NavBar from '@/components/Common/NavBar.vue'
import { leaveApi, uploadApi } from '@/api'

const router = useRouter()

// 请假类型选项
const leaveTypes = ['事假', '病假', '年假', '调休', '其他']

// 表单数据
const form = ref({
  type: '事假',
  title: '',
  startDate: '',
  endDate: '',
  reason: '',
  contactWay: '',
  attachments: [] as any[]
})

const loading = ref(false)
const showStartPicker = ref(false)
const showEndPicker = ref(false)
const startDateTime = ref(new Date())
const endDateTime = ref(new Date())

// 请假类型确认
const onTypeConfirm = (value: string) => {
  form.value.type = value
}

// 开始时间确认
const onStartConfirm = (value: Date) => {
  startDateTime.value = value
  form.value.startDate = formatDateTime(value)
  showStartPicker.value = false
}

// 结束时间确认
const onEndConfirm = (value: Date) => {
  endDateTime.value = value
  form.value.endDate = formatDateTime(value)
  showEndPicker.value = false
}

// 格式化日期时间
const formatDateTime = (date: Date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 附件上传后处理
const afterRead = async (file: any) => {
  try {
    const response = await uploadApi.uploadFile(file.file)
    file.url = response.data.url
  } catch (error) {
    showToast('文件上传失败')
    console.error('文件上传失败:', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  // 验证时间
  if (new Date(form.value.startDate) >= new Date(form.value.endDate)) {
    showToast('结束时间必须晚于开始时间')
    return
  }
  
  loading.value = true
  
  try {
    const data = {
      ...form.value,
      attachments: form.value.attachments.map(file => file.url).filter(Boolean)
    }
    
    await leaveApi.create(data)
    showToast('申请提交成功')
    router.back()
  } catch (error) {
    showToast('申请提交失败')
    console.error('申请提交失败:', error)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.leave-add-page {
  min-height: 100vh;
  background-color: #f1f1f1;
}

.page-content {
  padding: 16px;
}

.submit-section {
  margin-top: 24px;
  padding: 0 16px;
}
</style>